<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js数组之排序</title>
</head>
<body>
  <ul>
    <li>可利用sort函数对数组进行排序(升序或降序)</li>
    <li>如果是对象数组，则比对规则为其中某一个字段</li>
  </ul>
  <script>
    const arr = [1, 3, 2, 4, 6, 5]
    console.log(arr.sort(function (a, b) {
      return a - b // 升序
      // return b - a // 降序
    }))
    const cart = [
      { name: 'iphone', price: 8000 },
      { name: 'imac', price: 12000 },
      { name: 'ipad', price: 3688 }
    ]
    console.log(cart.sort(function (a, b) {
      return a.price - b.price
    }))
    // 自定义sort
    function sort(arr, func) {
      for (const i in arr) {
        for (const j in arr) {
          if (func(arr[i], arr[j]) < 0) {
            let temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
          }
        }
      }
      return arr
    }
    const nums = [1, 3, 2, 4, 6, 5]
    console.log(sort(nums, function (a, b) {
      return a - b
    }))
  </script>
</body>
</html>